package com.itttq.gen.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itttq.gen.model.po.AccountPo;
import com.itttq.gen.model.po.ProjectPo;
import com.itttq.gen.model.qo.ProjectQo;
import com.itttq.gen.model.to.IdsTo;
import com.itttq.gen.model.to.ResultTo;
import com.itttq.gen.service.ProjectService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.List;

@RestController
@RequestMapping("project")
@Api(tags = "project")
public class ProjectController extends BaseController {
    @Autowired
    private ProjectService projectService;

    /**
     * 保存到数据库。如果传入的对象有ID，则更新对象；没有ID则新增对象
     *
     * @param project 保存的对象
     */
    @PostMapping("/save")
    public String saveProject(@RequestBody @NotNull @Validated ProjectPo project) {
        AccountPo account = getAccount();
        project.setUpdater(account.getId());
        project.setUpdaterName(account.getName());
        if (null == project.getId()) {
            project.setCreator(account.getId());
            project.setCreatorName(account.getName());
            projectService.addProject(project);
        } else {
            projectService.updateProject(project);
        }
        // 保存成功后生成项目
        projectService.genProject(project, account);
        return project.getDownloadUrl();
    }

    /**
     * 根据ID删除记录
     *
     * @param id
     */
    @PostMapping("/del/{id}")
    public void del(@PathVariable("id") long id) {
        projectService.delProject(id);
    }

    /**
     * 根据ID获取单个对象信息
     *
     * @param id
     */
    @GetMapping("/project/{id}}")
    public ProjectPo project(@PathVariable("id") long id) {
        return projectService.getProject(id);
    }

    /**
     * 根据条件查询记录并分页
     *
     * @param projectQo 查询对象
     */
    @GetMapping("/projects")
    public IPage<ProjectPo> projects(ProjectQo projectQo) {
        return projectService.getProjectAndPage(projectQo);
    }

    /**
     * 根据条件查询记录不分页
     *
     * @param projectQo 查询对象
     */
    @GetMapping("/projectList")
    public List<ProjectPo> projectList(ProjectQo projectQo) {
        return projectService.getProjects(projectQo);
    }

    /**
     * 根据ID集合批量删除数据
     *
     * @param idsTo ID集合对象
     */
    @PostMapping("/delBatch")
    public void delBatch(@RequestBody IdsTo idsTo) {
        Assert.isTrue(null != idsTo && null != idsTo.getIds(), ResultTo.getCodeAndMsg(ResultTo.ResultCode.DATA_NO, "请选择要删除的记录"));
        projectService.delProjectByIds(idsTo.getIds());
    }

    /**
     * 根据ID生成项目
     *
     * @param id 项目ID
     */
    @PostMapping("/gen/{id}")
    public String genProject(@PathVariable("id") long id) {
        return projectService.genProject(id, getAccount()).getDownloadUrl();
    }
}
